package Almacenamiento;

import java.awt.print.Book;
import java.util.ArrayList;
import javax.print.DocFlavor.STRING;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class JDialogAgregarTuplas extends javax.swing.JDialog {
    DefaultTableModel modelTablaTuplas;
    RelacionFile rf;
    boolean registroTupla;
    boolean registroTodo;
    String w;
    ArrayList listaFilas;
    ArrayList listaIndexFilas;
    public JDialogAgregarTuplas(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        
        
        initComponents();
    }
    public JDialogAgregarTuplas(java.awt.Frame parent, boolean modal, RelacionFile rf) {
        super(parent, modal);
        initComponents();
        setTitle("Agregar tuplas a la relación: "+rf.getNameRelacion());
        this.rf = rf;
        listaFilas = new  ArrayList();
        listaIndexFilas = new ArrayList();
        PonerTuplasDeRelacion(this.rf);
        
    }
     private void PonerTuplasDeRelacion(RelacionFile rf){//flata
         //sirve para cargar losa tributos y datos de la relacion en la aplicacioon
        String [] encabezado = new String[rf.getRelacion().getAtributos().size()];        
        //los encabezados son dinamicos
        for (int i = 0; i < encabezado.length ; i++) {
            encabezado[i] = rf.getRelacion().getAtributo(i).getNombre();
        }
        modelTablaTuplas = new   DefaultTableModel(encabezado, 0);
        jtable_tuplas.setModel(modelTablaTuplas);
        //agregamos las tuplas que corresponden a esta relacion
         try {
             
             
         } catch (Exception e) {
             
             
         }
        
        
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jtable_tuplas = new javax.swing.JTable();
        btn_agregarTupla = new javax.swing.JButton();
        btn_Aceptar = new javax.swing.JButton();
        btn_salir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jtable_tuplas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtable_tuplas);

        btn_agregarTupla.setText("Agregar Tupla");
        btn_agregarTupla.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_agregarTuplaActionPerformed(evt);
            }
        });

        btn_Aceptar.setText("Guardar Tuplas");
        btn_Aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_AceptarActionPerformed(evt);
            }
        });

        btn_salir.setText("Salir");
        btn_salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_salirActionPerformed(evt);
            }
        });

        jLabel1.setText("jLabel1");

        jLabel2.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1245, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btn_agregarTupla, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_Aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(277, 277, 277)
                        .addComponent(jLabel1)
                        .addGap(88, 88, 88)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 471, Short.MAX_VALUE)
                        .addComponent(btn_salir, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btn_agregarTupla)
                            .addComponent(btn_Aceptar)
                            .addComponent(btn_salir)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private boolean  EsFilaValida(Object [] o){
        boolean filaValida = true;        
         w ="";
        for (int i = 0; i < rf.getRelacion().getNumeroDeAtributos(); i++) {
            Atributo at =  rf.getRelacion().getAtributo(i);
            w += at.getTipo().toString()+"\n";
            Class<? extends Comparable> tipo = at.getTipo();
            if (!EsCeldaValida(tipo, o[i])){
                filaValida = false;
                break;
            }
        }
        JOptionPane.showMessageDialog(null, w,"EEEERROR",0);
        return filaValida;
    }
    private boolean EsCeldaValida(Class<? extends Comparable> tipo, Object o){
        boolean esvalido = false;
        try {
            if (tipo.toString().compareTo("class java.lang.String")==0){
                String.valueOf(o);
            }else if(tipo.toString().compareTo("class java.lang.Character")==0){
                Character e = (Character)o;
            }else if(tipo.toString().compareTo("class java.lang.Byte")==0){
                Byte.parseByte(o.toString());
            }else if(tipo.toString().compareTo("class java.lang.Short")==0){
                Short.parseShort(o.toString());
            }else if(tipo.toString().compareTo("class java.lang.Integer")==0){
                Integer.parseInt(o.toString());
            }else if(tipo.toString().compareTo("class java.lang.Long")==0){
                Long.parseLong(o.toString());
            }else if(tipo.toString().compareTo("class java.lang.Float")==0){
                Float.parseFloat(o.toString());
            }else if(tipo.toString().compareTo("class java.lang.Double")==0){
                Double.parseDouble(o.toString());
            }
            esvalido = true;
        } catch (Exception e) {
            esvalido = false;
        }
        return esvalido;
    }
    private void GuardarTuplas(ArrayList lista){
        JOptionPane.showMessageDialog(null, "Guardando datos...","EEEERROR",0);

    }
    
    private void btn_agregarTuplaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_agregarTuplaActionPerformed
         Object [] o = new Object[modelTablaTuplas.getColumnCount()];
         listaIndexFilas.add(modelTablaTuplas.getRowCount());
         //listaFilas.add(o);
         modelTablaTuplas.addRow(o);
         btn_Aceptar.setVisible(true);
    }//GEN-LAST:event_btn_agregarTuplaActionPerformed
    private void btn_AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_AceptarActionPerformed
        //cargamos las nuevas filas a las lista para procesar
        listaFilas.clear();
        for (int i = 0; i < listaIndexFilas.size(); i++) {
            Object [] o = new Object[modelTablaTuplas.getColumnCount()];
            for (int j = 0; j < o.length; j++) {
                o[j] = modelTablaTuplas.getValueAt(Integer.parseInt(listaIndexFilas.get(i).toString()), j);
            }
            listaFilas.add(o);
           modelTablaTuplas.addRow(o);
        }

        jLabel2.setText(String.valueOf( listaFilas.size()));
        //primero verificamos si los datos de todas las filas son correctas
        boolean seguir = true;
        for (int i = 0; i < listaFilas.size(); i++) {
            Object [] fila = (Object [])listaFilas.get(i);
            if(!EsFilaValida(fila)){
                seguir = false;
                break;
            }
        }
        if (seguir){//una vez validado todas las tuplas a agregar guardamos en la base de datos
             Object [] fila = (Object [])listaFilas.get(0);
            jLabel1.setText(fila[0].toString());
            GuardarTuplas(listaFilas);
            listaFilas.clear();
            listaIndexFilas.clear();
            btn_Aceptar.setVisible(false);
        }
        else{
            JOptionPane.showMessageDialog(null, "Hay datos que no son correctos...","ERROR",0);
        }
    }//GEN-LAST:event_btn_AceptarActionPerformed
    private void btn_salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_salirActionPerformed
        if(registroTodo)
            this.setVisible(false);
        else{//guardamos las tuplas que no se han guardado
            
            
            this.setVisible(false);
        }
        
    }//GEN-LAST:event_btn_salirActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Aceptar;
    private javax.swing.JButton btn_agregarTupla;
    private javax.swing.JButton btn_salir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jtable_tuplas;
    // End of variables declaration//GEN-END:variables
}
